﻿using Org.BouncyCastle.Utilities.Encoders;
using PasswdTool.Model;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Tables;

namespace PasswdTool
{
    public partial class NewUserFrm : Form
    {
        public NewUserFrm()
        {
            InitializeComponent();
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OkBtn_Click(object sender, EventArgs e)
        {
            string name = nameTxb.Text;
            string passwd = passwdTxb.Text;
            string rePasswd = rePasswdTxb.Text;
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("用户不能为空!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                nameTxb.Focus();
                return;
            }
            if (string.IsNullOrEmpty(passwd))
            {
                MessageBox.Show("密码不能为空!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                passwdTxb.Focus();
                return;
            }
            if (string.IsNullOrEmpty(rePasswd))
            {
                MessageBox.Show("确认密码不能为空!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                rePasswdTxb.Focus();
                return;
            }
            if (!string.Equals(passwd, rePasswd))
            {
                MessageBox.Show("两次密码不一致!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                rePasswdTxb.Focus();
                return;
            }
            UserModel query = new UserModel()
            {
                Name = name
            };
            UserTable table = GlobalContainer.UserTable;
            List<UserModel> users = table.Query(query);
            if (users.Count > 0)
            {
                MessageBox.Show("用户已存在!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                nameTxb.Focus();
                return;
            }
            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(passwd));
            passwd = Base64.ToBase64String(bytes);
            UserModel model = new UserModel()
            {
                Name = name,
                Passwd = passwd,
                Encrypt = Generate.GenerateKey(16),
                IV = Generate.GenerateKey(16),
            };
            table.Insert(model);
            MessageBox.Show("新建成功!", "PasswdTool提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
    }
}
